<?php
/**
 * @Notes api公共接口类.
 * @author: ysongyang <ysongyang@qq.com>
 * @link
 * @copyright: copyright 2016 ysongyang all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
namespace app\index\controller;

use app\api\controller\PHPEmail;
use app\api\controller\ResUpload;
use think\Db;
use think\Session;

class Api extends Base{

    public $phpEmail;

    public function _initialize()
    {
        parent::_initialize();
        $this->phpEmail = new PHPEmail();
    }

    public function upload(){
        $upload = new ResUpload();
        $info=$upload->upload_attachment('attachment/');
        echo json_encode($info);
    }

    /**
     * 富文本编辑器图片上传
     */
    public function uploadatta(){
        $upload = new ResUpload();
        $info=$upload->upload_attachment();
        echo json_encode($info);
    }

    /**
     * 重新激活邮件
     */
    public function activate()
    {
        $email= request()->param('email');
        $username = Session::get('userinfo.username');
        $phpemail = new PHPEmail();
        $result = $phpemail->activate_send_mail($email, $username);
        if($result){
            $json = ['status'=>0,'msg'=>"已成功发送邮件"];
            return json($json);
        }
    }

    /**
     * 获得我的消息
     * 1、谁回复了我的帖子有多少条
     * 2、谁@我 有多少条
     * 点进去后，这些提示信息 要更新状态 为 已阅 表字段（isread）
     */
    public function msg_count()
    {
        /*$forum_count= Db::table('pe_forum_reply')->field('id')
            ->where('tid','IN',function($query){
                $query->table('pe_forum')->where('uid',$this->uid)->field('id');
            })
            ->select();*/

        $forum_count = Db::query('SELECT id FROM pe_forum_reply WHERE isdel=0 AND  uid !=:miuid and touid=0 AND isread=0 and tid in (SELECT id FROM pe_forum WHERE uid = :uid)',['miuid'=>$this->uid,'uid'=>$this->uid]);
        //echo Db::getLastSql();
        $reply_count = Db::query('SELECT id FROM pe_forum_reply WHERE isdel=0 AND isread = 0 AND touid = :uid',['uid'=>$this->uid]);
        $count = count($forum_count)+count($reply_count);
        if($count>=1){
            $result = array('status' => 0, 'count' => $count);
        }else{
            $result = array('status' => 0,'count'=>0);
        }
        return json($result);
    }

    /**
     * 将通知后的 回复消息 更新状态 为 已阅
     */
    public function msg_read()
    {
        $forum_count = Db::query('SELECT id FROM pe_forum_reply WHERE isdel=0  AND uid !=:miuid and touid = 0 AND isread=0 and tid in (SELECT id FROM pe_forum WHERE uid = :uid)',['miuid'=>$this->uid,'uid'=>$this->uid]);
        //echo Db::getLastSql();
        $reply_count = Db::query('SELECT id FROM pe_forum_reply WHERE isdel=0 AND isread = 0 AND  touid = :uid',['uid'=>$this->uid]);
        if(count($forum_count)>0){
            foreach($forum_count as $key=>$val){
                Db::table('pe_forum_reply')->where('id',$val['id'])->update(['isread'=>1]);
            }
        }
        if(count($reply_count)>0){
            foreach($reply_count as $key=>$val){
                Db::table('pe_forum_reply')->where('id',$val['id'])->update(['isread'=>1]);
            }
        }
        $result = array('status' => 0);
        return json($result);
    }

    /**
     * 读取我的消息
     */
    public function msg()
    {
        $noticeList= Db::query('SELECT * FROM pe_forum_reply WHERE isdel=0 AND uid !=:miuid AND noticeclear=1 AND  isread=1 and tid in (SELECT id FROM pe_forum WHERE uid =:uid) OR touid=:touid  AND noticeclear=1 ORDER BY reply_time desc',['miuid'=>$this->uid,'uid'=>$this->uid,'touid'=>$this->uid]);
        $user_model = new \app\model\User();
        $forum_model = new \app\model\Forum();
        if($noticeList){
            $rows=array();
            foreach($noticeList as $key=>$val){
                if($val['touid']==$this->uid){ //如果是@我的话
                    $rows[$key]['id']=$val['id'];
                    $rows[$key]['type']=1;
                    $title = $forum_model->search(['id'=>$val['tid']],'title');
                    $uname = $user_model->search(['id'=>$val['uid']],'username');
                    $rows[$key]['content'] = "<a href='".url('index/user/home',['uid'=>$val['uid']])."' target='_blank'>"."<cite>".$uname['username']."</cite></a> 在主题 <a href='".url('index/forum/detail',['tid'=>$val['tid']]).$val['floorid']."'  target='_blank'><cite>".$title['title']."</cite></a> 中回复了你";
                    $rows[$key]['href'] = url('index/forum/detail',['tid'=>$val['tid']]).$val['floorid'];
                    $rows[$key]['time'] = wordTime($val['reply_time']);
                    $rows[$key]['uid'] = $val['uid'];
                }else{
                    $rows[$key]['id']=$val['id'];
                    $rows[$key]['type']=1;
                    $title = $forum_model->search(['id'=>$val['tid']],'title');
                    $uname = $user_model->search(['id'=>$val['uid']],'username');
                    $rows[$key]['content'] = "<a href='".url('index/user/home',['uid'=>$val['uid']])."' target='_blank'>"."<cite>".$uname['username']."</cite></a> 回答了您的问答 <a href='".url('index/forum/detail',['tid'=>$val['tid']]).$val['floorid']."'  target='_blank'><cite>".$title['title']."</cite></a>";
                    $rows[$key]['href'] = url('index/forum/detail',['tid'=>$val['tid']]).$val['floorid'];
                    $rows[$key]['time'] = wordTime($val['reply_time']);
                    $rows[$key]['uid'] = $val['uid'];
                }
            }
            $result = array('status' => 0,"rows"=>$rows);
        }else{
            $result = array('status' => 0,"count"=>0,"pages"=>0,"rows"=>[]);
        }
        return json($result);

    }

    /**
     * 获取我的问答
     */
    public function mine_froum()
    {
        $uid = $this->uid;
        $data = model('forum')->search(['uid'=>$uid],"*",false);
        if(empty($data)){
            $result = array("status"=>0,"count"=>0,"rows"=>[]);
        }else{
            foreach($data as $key=>$val){
                $rows[$key]['title']=$val['title'];
                $rows[$key]['class'] = getCageName($val['cate_id'],'name'); //获取分类名称
                $rows[$key]['comment'] = getReplayCount($val['id']); //获取回复量
                $rows[$key]['experience'] = $val['experience'];
                $rows[$key]['hits'] = $val['view'];
                $rows[$key]['id'] = $val['id'];
                $rows[$key]['status'] = $val['elite']==1?1:0;
                $rows[$key]['accept'] = $val['accept']==1?1:0;
                $rows[$key]['time'] = $val['add_time'];
                $rows[$key]['uid'] = $val['uid'];
            }
            $result = array('status' => 0,"rows"=>$rows,"count"=>count($rows));
        }
        return json($result);
    }

    /**
     * 删除我的消息
     * noticeclear 字段更改为1
     */
    public function msg_del(){
        $result = array('status' => 0);
        $id = request()->param('id'); // 单个删除
        $type = request()->param('type'); //清空全部
        if($id){
            if(db('forum_reply')->where(['id'=>$id])->update(['noticeclear'=>-1])){
                $result = array('status' => 0);
            }
        }
        if($type){
            //查询当前我的消息
            $ids= Db::query('SELECT id FROM pe_forum_reply WHERE isdel=0 AND noticeclear=1 AND uid !=:miuid AND isread=1 and tid in (SELECT id FROM pe_forum WHERE uid =:uid) OR touid=:touid AND noticeclear=1  ORDER BY reply_time desc',['miuid'=>$this->uid,'uid'=>$this->uid,'touid'=>$this->uid]);
            $newIds=[];
            foreach($ids as $key=>$val){
                $newIds[] .=$val['id'];
            }
            $newIds = implode(",",$newIds);
            if(db('forum_reply')->where('id','in',$newIds)->update(['noticeclear'=>-1])){
                $result = array('status' => 0);
            }
        }
        return json($result);
    }
}